<template>
  <!--  -->
  <cl-crud ref="crud" @load="onLoad" :on-refresh="onRefresh">
    <cl-pagefull @resize="onResize">
      <template #head>
        <cl-title-module title="部门报表" sub-title="以部门人员为单位进行汇总（当前登陆账号所管理的部门）" :columns="tableData.columns"
          :print="printParams" v-model="tableData.columns" @export-file="exportExcel" />
        <el-row type="flex">
          <cl-filter-group v-model="search">

            <cl-filter label="事业部">
              <cl-select v-model="search.biz_id" placeholder="请选择" filterable @change="changeBiz">
                <el-option v-for="item in business" :key="item.biz_id" :label="item.biz_name" :value="item.biz_id" />
              </cl-select>
            </cl-filter>
            <cl-filter label="分公司">
              <cl-select v-model="search.company_id" placeholder="请选择" clearable filterable>
                <el-option label="全部" value="" />

                <el-option v-for="item in bizRefData.company" :key="item.company_id" :label="item.company_name"
                  :value="item.company_id" />
              </cl-select>
            </cl-filter>
            <cl-filter label="品牌">
              <cl-select v-model="search.bra_id" placeholder="全部" filterable clearable multiple collapse-tags>
                <el-option v-for="item in bizRefData.brand" :key="item.bra_id" :label="item.bra_name"
                  :value="item.bra_id" />
              </cl-select>
            </cl-filter>
            <cl-filter label="时间">
              <cl-date-picker v-model="search.date" type="daterange" range-separator="至" start-placeholder="开始日期"
                end-placeholder="结束日期" value-format="yyyy-MM-dd" style="width: 230px" :clearable="false" />
            </cl-filter>
            <cl-filter label="部门">
              <cl-cascader clearable v-model="search.dept_ids" :options="deptList" style="min-width: 230px"
                collapse-tags :props="{
                  multiple: true,
                  value: 'dept_id',
                  label: 'dept_name'
                }" filterable />
            </cl-filter>
          </cl-filter-group>
        </el-row>
      </template>

      <!-- 数据表格 -->
      <cl-table v-bind="tableData" id="deptReport" ref="table">
        <cl-empty slot="empty" />
      </cl-table>
    </cl-pagefull>
  </cl-crud>
</template>
<script>
import { exportExcel } from "@/utils/excel";
import { cloneDeep } from "cl-admin/utils";
import dayjs from "dayjs";
import { delEmptyChildren } from "@/utils";
export default {
  data() {
    return {
      printParams: {
        id: "deptReport",
        popTitle: "部门报表"
      },
      // 表格配置
      tableData: {
        "context-menu": ["refresh"],
        sortRefresh: false,
        columns: [],
        props: {
          rowKey: "dept_id",
          showSummary: true,
          summaryMethod: this.getSummaries,
          maxHeight: 500,
          treeProps: { children: 'children', hasChildren: 'hasChildren' }
        }
      },
      initColumns: [
        {
          type: "index",
          label: "#",
          align: "center",
          width: 50,
          fixed: true,
          disable: true
        },
        {
          label: "部门",
          prop: "dept_name",
          minWidth: 220,
          align: "left",
          showOverflowTooltip: true,
          fixed: true,
          // formatter: (row) => `${row.parent_dept_name} - ${row.dept_name}`
        },
        {
          label: "姓名",
          prop: "title",
          minWidth: 120,
          align: "left",
          showOverflowTooltip: true,
          fixed: true
        },
        { label: "加微数", prop: "wechat", sortable: false, minWidth: 130 },
        // { label: "重粉数", prop: "inherit_nums", sortable: true, minWidth: 130 },
        // {
        // 	label: "新客定金数",
        // 	prop: "deposit",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        {
          label: "实际定金人数",
          prop: "deposit_actually_person",
          sortable: false,
          minWidth: 150
        },
        {
          label: "0定金到店数",
          prop: "no_deposit_arrive",
          sortable: false,
          minWidth: 150
        },
        {
          label: "实际定金数",
          prop: "deposit_actually",
          sortable: false,
          minWidth: 150
        },
        {
          label: "实际定金率（人）",
          prop: "deposit_rate_actually",
          sortable: false,
          minWidth: 170,
          formatter: (row) => `${row.deposit_rate_actually}%`
        },
        {
          label: "排客人数",
          prop: "plan_arrive",
          sortable: false,
          minWidth: 170
        },
        {
          label: "流失人数",
          prop: "lost",
          sortable: false,
          minWidth: 170
        },
        {
          label: "新客到店人头数",
          prop: "arrive_person",
          sortable: false,
          minWidth: 160
        },
        {
          label: "新客到店率",
          prop: "deposit_arrive_radio",
          sortable: false,
          minWidth: 120
        },
        { label: "定金人数", prop: "deposit_person", sortable: false, minWidth: 120 },
        {
          label: "新客定金人数",
          prop: "deposit_new_person",
          sortable: false,
          minWidth: 150
        },
        {
          label: "定金率（人）",
          prop: "deposit_rate",
          sortable: false,
          minWidth: 140,
          formatter: (row) => `${row.deposit_rate}%`
        },
        // {
        // 	label: "定金率（数）",
        // 	prop: "deposit_rate_count",
        // 	sortable: true,
        // 	minWidth: 140,
        // 	formatter: (row) => `${row.deposit_rate_count}%`
        // },
        {
          label: "加微到店率",
          prop: "wechat_arrive_radio",
          sortable: false,
          minWidth: 120,
          formatter: (row) => `${row.wechat_arrive_radio}%`
        },
        { label: "到店人数", prop: "total_arrived", sortable: false, minWidth: 120 },
        // {
        // 	label: "加微率",
        // 	prop: "wechat_rate",
        // 	sortable: true,
        // 	minWidth: 120,
        // 	formatter: (row) => `${row.wechat_rate}%`
        // },
        // {
        // 	label: "平台加微数",
        // 	prop: "",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        // {
        // 	label: "平台定金数",
        // 	prop: "",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        // {
        // 	label: "平台定金率",
        // 	prop: "",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        // {
        // 	label: "退定金数",
        // 	prop: "deposit_refuse",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        // {
        // 	label: "退定金人数",
        // 	prop: "deposit_refuse_person",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        // {
        // 	label: "退定金率",
        // 	prop: "deposit_refuse_rate",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        // {
        // 	label: "实际定金数",
        // 	prop: "deposit_actually",
        // 	sortable: true,
        // 	minWidth: 120
        // },
        // {
        // 	label: "实际定金单价（￥）",
        // 	prop: "deposit_price_actually",
        // 	sortable: true,
        // 	minWidth: 190
        // },
        {
          label: "新客业绩（￥）",
          prop: "achieve_new_customer",
          sortable: false,
          minWidth: 150
        },
        {
          label: "老转新业绩（￥）",
          prop: "achieve_old_new",
          sortable: false,
          minWidth: 200
        },
        {
          label: "新客到店客单（￥）",
          prop: "arrive_person_price",
          sortable: false,
          minWidth: 190
        }
      ],
      search: {
        biz_id: "",
        company_id: "",
        date: [
          dayjs().startOf("day").format("YYYY-MM-DD"),
          dayjs().endOf("day").format("YYYY-MM-DD")
        ],
        begin_time: "",
        end_time: "",
        bra_id: [],
        dept_ids: [],
        type: "pre"
      },
      deptList: [] //部门
    };
  },
  computed: {
    bizRefData() {
      const { biz_id } = this.search;
      return this.getBizRefData(biz_id);
    }
  },
  created() {
    this.search.biz_id = this.getCurrBiz();
    this.init();
    // this.tableData.columns = cloneDeep(this.initColumns);
  },
  methods: {
    async onRefresh(params, { next, done, render }) {
      // console.log('触发这里');
      let { title, data } = await next(params);

      console.log(data, '页面bug', title);
      let columns = (title ?? []).map((v, i) => {
        return {
          disable: i == 0,
          fixed: i == 0 || v.fixed ? true : false,
          prop: v.key,
          label: v.value,
          minWidth: 170,
          sortable: true
        };
      });
      this.initColumns = columns;
      !this.tableData.columns.length && (this.tableData.columns = columns);
      render(data);
    },
    async onLoad({ ctx, app }) {
      ctx.service(this.$service.preSale)
        .set("dict", {
          api: {
            page: "reportDeptTree"
          }
        })
        .done()
      app.refresh(this.search);
    },
    // crud刷新
    refresh() {
      this.$refs.crud.refresh({ page: 1, ...this.search });
      this.$nextTick(() => {
        this.$refs.table?.calcMaxHeight?.();
      });
    },
    onResize(h) {
      this.tableData.props.maxHeight = h;
    },
    // 表格合计
    getSummaries({ columns, data }) {
      let wechatSum = 0,
        depositSum = 0,
        actionSum = 0,
        achieve_new_customer = 0,
        arrive_person = 0,
        deposit = 0,
        deposit_refuse = 0,
        deposit_actually_person = 0;
      let arr = ["parent_dept_name", "title"];
      return columns.map((column, index) => {
        if (index === 0) {
          return "合计";
        }
        if (arr.includes(column.property)) return "";
        if (column.property === "wechat_arrive_radio") {
          if (wechatSum) {
            const _values = data.map((item) => Number(item['arrive_person']));
            let _arrive_person = _values.reduce((prev, curr) => {
              const value = Number(curr);
              if (!isNaN(value)) {
                return prev + curr;
              }
              return prev;
            }, 0);
            let result = _arrive_person / wechatSum
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        if (column.property === "month_wechat_arrive_radio") {
          const month_wechat_value = data.map((item) => Number(item['month_wechat']));
          const month_wechat = month_wechat_value.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + curr : prev;
          }, 0);

          const month_arrive_person_value = data.map((item) => Number(item['month_arrive_person']));
          const month_arrive_person = month_arrive_person_value.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + curr : prev;
          }, 0);

          if (month_wechat) {
            let result = month_arrive_person / month_wechat
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        if (column.property === "deposit_rate") {
          if (wechatSum) {
            let result = depositSum / wechatSum;
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        if (column.property === "deposit_rate_actually") {
          if (wechatSum) {
            let result = deposit_actually_person / wechatSum;
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        if (column.property === "deposit_rate_count") {
          if (wechatSum) {
            let result = deposit / wechatSum;
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        if (column.property === "wechat_rate") {
          if (actionSum) {
            let result = wechatSum / actionSum;
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        if (column.property === "deposit_refuse_rate") {
          if (depositSum) {
            let result = deposit_refuse / depositSum;
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        if (column.property === "arrive_person_price") {
          if (arrive_person) {
            let result = achieve_new_customer / arrive_person;
            return this.toFixed(result);
          } else {
            return 0;
          }
        }
        if (column.property === "month_deposit_rate") {
          const month_deposit_value = data.map((item) => Number(item['month_deposit']));
          const month_deposit = month_deposit_value.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + curr : prev;
          }, 0);

          const month_wechat_value = data.map((item) => Number(item['month_wechat']));
          const month_wechat = month_wechat_value.reduce((prev, curr) => {
            const value = Number(curr);
            return !isNaN(value) ? prev + curr : prev;
          }, 0);

          if (month_wechat) {
            let result = month_deposit / month_wechat;
            return this.toFixed(result * 100) + "%";
          } else {
            return 0 + "%";
          }
        }
        const values = data.map((item) => Number(item[column.property]));
        let sum = values.reduce((prev, curr) => {
          const value = Number(curr);
          if (!isNaN(value)) {
            return prev + curr;
          }
          return prev;
        }, 0);
        if (column.property === "wechat") {
          wechatSum = sum;
        }
        if (column.property === "deposit_person") {
          depositSum = sum;
        }
        if (column.property === "deposit") {
          deposit = sum;
        }
        if (column.property === "action") {
          actionSum = sum;
        }
        if (column.property === "achieve_new_customer") {
          achieve_new_customer = sum;
        }
        if (column.property === "arrive_person") {
          arrive_person = sum;
        }
        if (column.property === "deposit_refuse") {
          deposit_refuse = sum;
        }
        if (column.property === 'deposit_actually_person') {
          deposit_actually_person = sum;
        }
        return this.toFixed(sum);
      });
    },
    async initData() {
      const { biz_id } = this.search;
      this.deptList = delEmptyChildren(
        (await this.$store.dispatch("common/getDept", {
          biz_id,
          post: 1,
          needAll: false,
          needCascader: true
        })) || []
      );
    },
    async init() {
      const { biz_id } = this.search;
      this.getBizRefBrand(biz_id);
      this.getBizRefCompany(biz_id);
      this.initData();
    },
    //切换事业部
    changeBiz() {
      this.search.bra_id = [];
      this.search.company_id = "";
      this.search.dept_ids = [];
      this.init();
      // this.refresh();
    },
    // 导出EXCEl
    exportExcel() {
      exportExcel("#deptReport");
    }
  }
};
</script>
<style lang="scss" scoped>
::v-deep {
  .el-table--scrollable-x {
    .el-table__body-wrapper {
      z-index: 2;
    }
  }
}
</style>
